package xj.toolkit.netty.handler.callback;

import com.google.common.cache.Cache;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import xj.toolkit.util.Identifier;
import xj.toolkit.util.Identifyable;

import org.apache.commons.collections4.Closure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IdCallbackResponseHandler<I extends Identifyable> extends ChannelInboundHandlerAdapter {
	private static Logger logger = LoggerFactory.getLogger(IdCallbackResponseHandler.class);

	private Cache<Integer, Closure> uuidCache;

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		logger.debug("hey,channelActive");
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		logger.debug("channelInactive");
	}

	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		logger.warn("", cause);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		logger.debug("message received : {}", msg);
		Identifier<?> uuid = ((I) msg).getIdentification();
		Closure closure = uuidCache.getIfPresent(uuid);
		if (closure != null) {
			closure.execute(msg);
			uuidCache.invalidate(uuid);
		} else {
			logger.warn("can't find matched uuid {}", uuid);
		}
	}

	public void setUuidCache(Cache<Integer, Closure> uuidCache) {
		this.uuidCache = uuidCache;
	}
}
